# coding=utf-8
import datetime

from django.contrib.auth.models import AbstractUser
from django.db import models
from geopy.distance import great_circle

import settings
from social.enums import GenderEnum
from social.utils import upload_path
from social.utils.models import BaseModel, UserManager


class User(AbstractUser, BaseModel):
    TAG_GUARD = "guard"
    TAG_GUARD_DISABLE = "guard_disable"
    TAG_DISABLE_ING = "disable_ing"
    TAG_DISABLE = "disable"  # 注销
    password = models.CharField(null=True, max_length=128)
    phone = models.CharField(max_length=15, null=True, unique=True)
    phone_code = models.IntegerField(default=0)
    nickname = models.CharField(max_length=50, unique=True, null=True)
    bio = models.TextField(default='')
    uid = models.IntegerField(unique=True, null=True)
    city = models.CharField(null=True, max_length=10)
    avatar = models.ImageField(upload_to=upload_path.user_avatar_path, null=True, blank=True)  # 头像
    avatar_real = models.BooleanField(default=False)
    gender = models.CharField(max_length=1, choices=GenderEnum.choices(), default=GenderEnum.unknown.value)  # 性别
    birthday = models.DateField(blank=True, null=True)  # 生日
    lat = models.FloatField(default=0)
    lng = models.FloatField(default=0)
    hide_location = models.BooleanField(default=False)
    hide_last_active = models.BooleanField(default=False)
    last_active = models.DateTimeField(auto_now_add=True)
    height = models.IntegerField(default=0)
    weight = models.IntegerField(default=0)
    role = models.CharField(max_length=10, null=True)
    job = models.IntegerField(default=0)  # 行业
    follow_count = models.IntegerField(default=0)
    fans_count = models.IntegerField(default=0)
    friend_count = models.IntegerField(default=0)
    relationship = models.IntegerField(default=0)
    photos = models.TextField(default='')
    be_like_count = models.IntegerField(default=0)
    avatar_auth = models.BooleanField(default=False)
    vip_expired_time = models.DateTimeField(null=True)
    objects = UserManager()

    def update_location(self, lat, lng, save=False):
        if self.lat and self.lng:
            m = great_circle((self.lat, self.lng), (lat, lng)).meters
            if m < 10.0:
                return

        self.lat = max(-90.0, min(90.0, float(lat)))
        self.lng = max(-180.0, min(180.0, float(lng)))
        if save:
            self.save(update_fields=['lat', 'lng'])

    def buy_vip(self, product):
        from social.payment.models import Product
        if product.type == Product.VIP:
            now = datetime.datetime.now()
            if product.month == 12:
                days = 366
            else:
                days = int(31 * product.month)
            if days:
                if not self.vip_expired_time or (self.vip_expired_time.timestamp() <= now.timestamp()):
                    self.vip_expired_time = now + datetime.timedelta(days=days)
                else:
                    self.vip_expired_time = self.vip_expired_time + datetime.timedelta(days=days)
                self.save(update_fields=['vip_expired_time'])

    def update_avatar_real(self, avatar_real):
        if self.avatar_real != avatar_real:
            self.avatar_real = avatar_real
            self.save(update_fields=['avatar_real'])

    def update_avatar_auth(self, avatar_auth):
        if self.avatar_auth != avatar_auth:
            self.avatar_auth = avatar_auth
            self.save(update_fields=['avatar_auth'])

    def update_latlng(self, lat, lng):
        self.lat = lat
        self.lng = lng
        self.save(update_fields=['lat', 'lng'])

    @property
    def is_robot(self):
        return self.first_name == 'robot'

    @property
    def is_guard(self):
        # 督查
        return self.first_name == self.TAG_GUARD

    @property
    def is_admin(self):
        return self.first_name == 'admin'

    @property
    def is_disabled(self):
        # 注销了
        return self.first_name == self.TAG_DISABLE_ING

    @property
    def im_id(self):
        if self.is_admin:
            return 'admin'
        return f'{settings.APP_NAME}_{self.id}'

    @property
    def is_vip(self):
        return self.vip_expired_time and (
                self.vip_expired_time.timestamp() > datetime.datetime.now().timestamp())

    @classmethod
    def get_user_by_im_id(cls, im_id):
        _id = im_id[len(settings.APP_NAME) + 1]
        from social.utils.shortcut import get_object_or_none
        return get_object_or_none(User, id=_id)

    def save(self, *args, **kwargs):
        super(User, self).save(*args, **kwargs)
        if not self.uid and self.id:
            self.uid = f'00{200000 + self.id}'
            self.save(update_fields=['uid'])


class UserRegister(BaseModel):
    user_id = models.IntegerField(default=0, primary_key=True)
    channel = models.CharField(max_length=20, default='')
    install_data = models.TextField(default='')
    user_agent = models.TextField(default='')
    ip = models.GenericIPAddressField(null=True)

    market = models.CharField(max_length=20, null=True)
    device = models.CharField(max_length=100, null=True)
    system = models.CharField(max_length=20, null=True)
    system_version = models.CharField(max_length=20, null=True)
    app_version = models.CharField(max_length=20, null=True)
    did = models.CharField(max_length=100, null=True)
